<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\material;

use app\command\BaseWork;
use app\enum\AnalysisEnum;
use app\service\analysis\data\material\MaterialDayStatService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class MaterialDayStatWork extends BaseWork
{
    public const REDIS_TASK_KEY = AnalysisEnum::TASK_QUEUE_LIST['material_day_stat'];

    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_material_day_stat_work');
        // 设置参数
        $this->setDescription('数据分析-系统素材日汇总')
            ->addArgument('media_id', Argument::REQUIRED, '媒体类型 1：巨量 2：磁力  5：广点通')
            ->addArgument('type', Argument::REQUIRED, '类型 2：视频  3：图片')
            ->setHelp('php think analysis_material_day_stat_work [media_id] [type]');
    }

    /**
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $mediaId = intval($input->getArgument('media_id'));
        $taskType = intval($input->getArgument('type'));

        $redis = Cache::store('redis')->handler();
        $obj = new MaterialDayStatService();
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            $fields = $redis->hKeys(self::REDIS_TASK_KEY[$taskType][$mediaId]);
            if (! $fields) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                continue;
            }
            foreach ($fields as $field) {
                try {
                    $data = $redis->hGet(self::REDIS_TASK_KEY[$taskType][$mediaId], $field);
                    $arr = json_decode($data, true);
                    $this->getOutputMessage('汇总[' . $arr[2] . ']开始');
                    if (! $obj->runTask($arr)) {
                        $this->getOutputMessage('汇总[' . $arr[2] . ']失败:' . $obj::getError(0));
                    } else {
                        $redis->hDel(self::REDIS_TASK_KEY[$taskType][$mediaId], $field);
                    }
                    $this->getOutputMessage('汇总[' . $arr[2] . ']完成');
                } catch (\Exception $e) {
                    $this->getOutputMessage('错误：' . $e->getMessage());
                    echo $e->getLine() . PHP_EOL;
                    echo $e->getFile() . PHP_EOL;
                    echo $e->getTraceAsString() . PHP_EOL;
                }
            }
        }
        $this->getOutputMessage('系统素材日汇总结束');
    }
}
